package com.swl.juc.Executor;

import java.util.concurrent.*;

public class SemaphoreExecutorTest {

    private static int sum;

    private static Semaphore semaphore;

    public void doSome() {
        //创建一个核心线程数为4的线程池
        ExecutorService executorService = new ThreadPoolExecutor(4, 10,
                60L, TimeUnit.SECONDS,
                new ArrayBlockingQueue(10));

        semaphore = new Semaphore(2);

        executorService.execute(() -> {
            //第一个子任务
            try {
                semaphore.acquire();
                sum++;
                System.out.println(Thread.currentThread().getName() + ":1");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        });

        executorService.execute(() -> {
            //第二个子任务
            try {
                semaphore.acquire();
                sum += 2;
                System.out.println(Thread.currentThread().getName() + ":2");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                semaphore.release();
            }
        });

        executorService.execute(() -> {
            //第三个子任务
            try {
                semaphore.acquire();
                sum += 3;
                System.out.println(Thread.currentThread().getName() + ":3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        });
        executorService.execute(() -> {
            //第三个子任务
            try {
                semaphore.acquire();
                sum += 4;
                System.out.println(Thread.currentThread().getName() + ":4");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        });
        executorService.shutdown();
    }

    public static void main(String[] args) {
        SemaphoreExecutorTest executor = new SemaphoreExecutorTest();
        executor.doSome();
    }
}
